import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';

import { LoginParams, UserToken, UserInfo } from '../modes';

@Injectable()
export class UserService {

  constructor(
    private http: HttpClient
  ) { }
  

  login(params: LoginParams): Observable<UserToken> {
    return this.http.post(
      '/platform/api/users/login',
      params
    ).pipe(
      map((data: UserToken) => data),
      catchError((error: HttpErrorResponse) => Observable.throw(error))
    );
  }

  userInfo(userToken: UserToken): Observable<UserInfo> {
    return this.http.get(
      `/platform/api/users/${userToken.userId}?access_token=${userToken.id}`
    ).pipe(
      map((data: UserInfo) => {
        if(!data.resourceTrees) {
          data = { 
            ...data, 
            resourceTrees: {
              pro: [],
              own: [],
              public: []
            } 
          };
        }
        return data;
      }),
      catchError(error => Observable.throw(error))
    );
  }

  logout(userToken: UserToken): Observable<any> {
    return this.http.post(
      `/platform/api/users/logout?access_token=${userToken.id}`, 
      {}
    ).pipe(
      catchError(error => Observable.throw(error))
    );
  }

}
